package cn.lby.tp.downloadtest.fragment;

import static down.Utils.createDownloadTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.liulishuo.okdownload.DownloadTask;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import cn.lby.tp.downloadtest.R;
import cn.lby.tp.downloadtest.interfaces.MyOnLongClickListener;
import cn.lby.tp.downloadtest.interfaces.MyOnclickListener;
import down.DownLoaderHelper;
import down.DownLoaderManger;
import down.MyDownloadListener4WithSpeed;
import download_temp.FileInfo;
import download_temp.view.NumberProgressBar;


public class DownCurrentFragment extends Fragment {
    private View view;

    private Context context;
    private RecyclerView r1;
    private MyRecyclerView adapter;
    private List<FileInfo> fileInfoList;
    private HashMap<String, DownloadTask> map = new HashMap<>();
    private DownLoaderManger downLoaderManger;
    // 接口实例
    private Callbacks callbacks;

    // Fragment内部回调接口
    public interface Callbacks {
        void onItemSelected();
    }

    public void setCallbacks(Callbacks callbacks) {
        this.callbacks = callbacks;
    }

    public List<FileInfo> getFileInfoList() {
        return fileInfoList;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    public DownCurrentFragment() {
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        downLoaderManger = DownLoaderManger.getInstance(new DownLoaderHelper(context));
        // 获取所有下载中的任务
        fileInfoList = downLoaderManger.getAllDownloading();
        adapter = new MyRecyclerView(context, fileInfoList);

        // 监听单击事件
        adapter.setOnclickListener(position -> {
            down(position);
        });

        // 监听长按事件
        adapter.setLongClickListener((position, handler) -> {
            FileInfo fileInfo = fileInfoList.get(position);

            DownloadTask task = map.get(fileInfo.getFileName());
            if (task != null) {
                task.cancel();
                map.remove(task);
            }
            // 删除后更新
            fileInfoList.remove(fileInfo);
            downLoaderManger.delete(fileInfo);
            adapter.notifyAdapter(fileInfoList, false);
            Toast.makeText(context, "任务已删除", Toast.LENGTH_SHORT).show();
        });


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_down_current, container, false);
            r1 = view.findViewById(R.id.r1);
            r1.setItemAnimator(null);
            r1.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
            r1.setAdapter(adapter);
        }
        return view;
    }


    // 下载列表适配器
    static class MyRecyclerView extends RecyclerView.Adapter<MyRecyclerView.MyRecyclerViewHandler> {
        private Context context;
        private List<FileInfo> list;
        private MyRecyclerViewHandler handler;

        public MyRecyclerView(Context context, List<FileInfo> itemInfos) {
            this.context = context;
            this.list = itemInfos;
        }



        @SuppressLint("NotifyDataSetChanged")
        public void notifyAdapter(List<FileInfo> list, boolean isAdd) {
            if (!isAdd) {
                this.list = list;
            } else {
                this.list.addAll(list);
            }
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public MyRecyclerViewHandler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.down_item, parent, false);
            MyRecyclerViewHandler viewHandler = new MyRecyclerViewHandler(view);
            this.handler = viewHandler;
            return viewHandler;
        }

        @Override
        public void onBindViewHolder(@NonNull MyRecyclerViewHandler holder, int position) {
            FileInfo item = list.get(position);
            holder.title.setText(item.getFileName());
            float progress = (float) item.getFinished() / item.getLength() * 100;
            holder.pb.setProgress((int) progress);
        }

        @Override
        public int getItemCount() {
            return list == null ? 0 : list.size();
        }


        private MyOnclickListener onclickListener;
        private MyOnLongClickListener<MyRecyclerViewHandler> longClickListener;
        public void setOnclickListener(MyOnclickListener onclickListener) {
            this.onclickListener = onclickListener;
        }

        public void setLongClickListener(MyOnLongClickListener<MyRecyclerViewHandler> longClickListener) {
            this.longClickListener = longClickListener;
        }

        class MyRecyclerViewHandler extends RecyclerView.ViewHolder {
            private TextView title, state;
            private NumberProgressBar pb;
            public MyRecyclerViewHandler(@NonNull View itemView) {
                super(itemView);
                this.title = itemView.findViewById(R.id.name);
                this.pb = itemView.findViewById(R.id.pb);
                this.state = itemView.findViewById(R.id.state);
                itemView.setOnClickListener(v -> {
                    if (list != null) {
                        onclickListener.click(getPosition());
                    }
                });
                
                itemView.setOnLongClickListener(v -> {
                    longClickListener.longClick(getPosition(), this);
                    return true;
                });
            }
        }
    }

    private void down(int position) {
        View v = Objects.requireNonNull(r1.getLayoutManager()).findViewByPosition(position);
        FileInfo itemInfo = fileInfoList.get(position);
        NumberProgressBar pb = v.findViewById(R.id.pb);
        TextView state = v.findViewById(R.id.state);
        MyDownloadListener4WithSpeed listener4WithSpeed = new MyDownloadListener4WithSpeed(itemInfo, pb, state);

        // 下载成功
        listener4WithSpeed.setCallback((it) -> {
            // 删除后更新
            fileInfoList.remove(it);
            adapter.notifyAdapter(fileInfoList, false);
        });
        downHandler(itemInfo, listener4WithSpeed);
    }

    // 处理：下载、暂停、完成
    private void downHandler(FileInfo itemInfo, MyDownloadListener4WithSpeed listener4WithSpeed) {
        DownloadTask task = map.get(itemInfo.getFileName());
//        // 0：没有下载  1：下载中  2：暂停  3：完成
        int status = itemInfo.status;
        if (status == 0) { // 没有下载
            if (task == null) {
                task = createDownloadTask(itemInfo);
                map.put(itemInfo.getFileName(), task);
            }
            // 开始下载任务
            task.enqueue(listener4WithSpeed);
            itemInfo.status = 1; // 更改状态为下载中
        } else if (status == 1) {
            if (task != null) {
                // 取消任务
                task.cancel();
            }
            itemInfo.status = 2; // 更改状态为暂停中
        } else if (status == 2) {
            if (task != null) {
                task.enqueue(listener4WithSpeed);
            }
            itemInfo.status = 1;
        } else if (status == 3 ) {
            Toast.makeText(context, "该资源已经下载完成", Toast.LENGTH_SHORT).show();
        }
    }

    // 添加一个下载任务
    public void addTask(String name, String url) {
        FileInfo info = new FileInfo(name, url);
        info.setLength(0);
        info.setFinished(0);
        downLoaderManger.addTask(info);
    }

    // 任务全部开始
    public void startDownAllTask() {
        for (int i = 0; i < fileInfoList.size(); i++) {
            down(i);
        }
    }

    // 任务全部开始
    public void cancelDownAllTask() {
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
        for (FileInfo fileInfo : fileInfoList) {
            downLoaderManger.delete(fileInfo);
        }
        map.clear();
        fileInfoList.clear();
        recyclerViewNotify(fileInfoList);
    }

    private void recyclerViewNotify(List<FileInfo> list) {
        adapter.notifyAdapter(list, false);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public void recyclerViewNotify() {
        if (fileInfoList != null) {
            fileInfoList = downLoaderManger.getAllDownloading();
            recyclerViewNotify(fileInfoList);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //OkDownload.with().downloadDispatcher().cancelAll();
        for (String key : map.keySet()) {
            DownloadTask task = map.get(key);
            if (task != null) {
                task.cancel();
            }
        }
    }
}